/*
 * ImageViewer.java
 *
 * Created on December 18, 2007, 10:33 PM
 */

package imageViewer;

import editor.MyCanvas;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.InputStream;
import java.sql.Blob;
import java.util.Iterator;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
import javax.swing.JFileChooser;
import oracle.jdbc.driver.OraclePreparedStatement;
import oracle.jdbc.driver.OracleResultSet;
import oracle.ord.im.OrdImage;

/**
 * 
 * @author Daniel Peka?, xpekar04 a David Gargul?k, xgargu01
 */
public class ImageViewer extends javax.swing.JDialog {
    private BufferedImage myImage;
    private editor.MyCanvas canvas;
    private JFileChooser fcLoad;
    private JFileChooser fcSave;
  
    /** Creates new form ImageViewer */
    public ImageViewer(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        myImage = null;
//        jMenu1.getPopupMenu().setDefaultLightWeightPopupEnabled(false);
        //Dimension d = jPanel1.getSize();
//        myImage = new BufferedImage(d.width, d.height, BufferedImage.TYPE_INT_RGB);
        canvas = new MyCanvas();
        canvas.setImage(myImage);
  
        fcLoad = new JFileChooser();
        fcLoad.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                LoadImage(evt);
            }
        });
        scrollPane1.add(canvas);
        this.setTitle("Image Viewer");
          
        
    }
 private void LoadImage(java.awt.event.ActionEvent evt){
        // this may free up some memory, before new image is created
        myImage = null;
        canvas.setImage(null);
        // force garbage collection, to free some memory
        System.runFinalization();
        System.gc();
        File f = fcLoad.getSelectedFile();
        try {
        myImage = ImageIO.read(f);
        } catch (Exception ex)
        {
//            myCanvas1.invalidateImage();
//            Error("Problem loading file!");
            return;
        }
        if(myImage==null)
        {
//            myCanvas1.invalidateImage();
//            Error("Problem loading file, invalid format?!");
            return;
        }
        canvas.setImage(myImage);
        canvas.update(canvas.getGraphics());
        scrollPane1.setScrollPosition(0,0);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
    private void initComponents() {
        scrollPane1 = new java.awt.ScrollPane();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setName("Image Viewer");

        jButton1.setText("Load");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Finish");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(scrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 376, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 240, Short.MAX_VALUE)
                        .addComponent(jButton2)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(scrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 268, Short.MAX_VALUE)
                .addContainerGap())
        );
        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        this.setVisible(false);
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        fcLoad.showOpenDialog(this);      
    }//GEN-LAST:event_jButton1ActionPerformed
    
    /**
     * Set image to be displayed
     */
    public void setImage(BufferedImage img) {
        myImage = img;
        canvas.setImage(myImage);
        canvas.update(canvas.getGraphics());
        scrollPane1.setScrollPosition(0,0);
    }

    /**
     * Get the image displayed in the viewer
     * @return The image
     */
    public BufferedImage getImage() {
        return myImage;
    }
    
    /**
     * Load image from DB that is returned with the query
     */
    public void loadQuery(OraclePreparedStatement stmt) {
        try {
            OracleResultSet res = (OracleResultSet) stmt.executeQuery();
            if(res.next()) {
                OrdImage image = (OrdImage)res.getCustomDatum(1,OrdImage.getFactory());
                Blob blob = (java.sql.Blob)image.getContent();
                InputStream in = blob.getBinaryStream();
                myImage = ImageIO.read( in );
                canvas.setImage(myImage);
                canvas.update(canvas.getGraphics());
                scrollPane1.setScrollPosition(0,0);
            }
            
        }
        catch(Exception e) {
                
        }
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ImageViewer(new javax.swing.JFrame(), true).setVisible(true);
            }
        });
    }
    
    /**
     * Generate thumbnail
     */
    public static void doThumb( BufferedImage input, ImageOutputStream os, int boxSize )
  {
    try
    {
      // Read the source file
   
      // Get the original size of the image
      int srcHeight = input.getHeight();
      int srcWidth = input.getWidth();

      // Constrain the thumbnail to a predefined box size
      int height = boxSize;
      int width = boxSize;
      if( srcHeight > srcWidth )
      {
        width = ( int )( ( ( float )height / ( float )srcHeight ) * ( float )srcWidth );
      }
      else if( srcWidth > srcHeight )
      {
        height = ( int )( ( ( float )width / ( float )srcWidth ) * ( float )srcHeight );
      }

      // Create a new thumbnail BufferedImage
      BufferedImage thumb = new BufferedImage( width, height, BufferedImage.TYPE_USHORT_565_RGB );
      Graphics g = thumb.getGraphics();
      g.drawImage( input, 0, 0, width, height, null );

      // Get Writer and set compression
      Iterator iter = ImageIO.getImageWritersByFormatName( "JPG" );
      if( iter.hasNext() ) 
      {
        ImageWriter writer = (ImageWriter)iter.next();
        ImageWriteParam iwp = writer.getDefaultWriteParam();
        iwp.setCompressionMode( ImageWriteParam.MODE_EXPLICIT );
        iwp.setCompressionQuality( 0.75f );
        writer.setOutput( os );
        IIOImage image = new IIOImage(thumb, null, null);
        writer.write(null, image, iwp);
      }
    }
    catch( Exception e )
    {
      e.printStackTrace();
    }
  }
  
    /**
     * Generate the image
     */
  public static void doImage( BufferedImage input, ImageOutputStream os )
  {
    try
    {
      // Read the source file
   
      // Get the original size of the image

      // Get Writer and set compression
      Iterator iter = ImageIO.getImageWritersByFormatName( "JPG" );
      if( iter.hasNext() ) 
      {
        ImageWriter writer = (ImageWriter)iter.next();
        ImageWriteParam iwp = writer.getDefaultWriteParam();
        iwp.setCompressionMode( ImageWriteParam.MODE_EXPLICIT );
        iwp.setCompressionQuality( 0.75f );
        writer.setOutput( os );
        IIOImage image = new IIOImage(input, null, null);
        writer.write(null, image, iwp);
      }
    }
    catch( Exception e )
    {
      e.printStackTrace();
    }
  }
  
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private java.awt.ScrollPane scrollPane1;
    // End of variables declaration//GEN-END:variables
    
}
